package com.zoweunion.mechanic.controller;

import com.github.pagehelper.PageInfo;
import com.zoweunion.mechanic.model.ResponseBean;
import com.zoweunion.mechanic.service.WirelessDeviceService;
import com.zoweunion.mechanic.util.MD5;
import com.zoweunion.mechanic.util.MyException;
import com.zoweunion.mechanic.util.constants.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/wirelessDevice")
public class WirelessDeviceController extends BaseController{

    @Autowired
    private WirelessDeviceService wirelessDeviceService;

    /**
     * @describe 无线设备光感报警接口
     * @param  deviceId
     * */
    @PostMapping("/lightSenseWarning")
    public void lightSenseWarning(String deviceId, String currentDateMD5Str) throws ParseException {
        // 验证加密日期是否一致;前后端约定:以加密当天日期来提升安全性
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String currentDate = dateFormat.format(date); // 当前年月日
        String md5Str = currentDate + dateFormat.parse(currentDate).getTime();

        // MD5加密字符为：当前年月日 + 当前年月日的时间戳，例: 20220903 + 1662134400000 - 202209031662134400000
        if(currentDateMD5Str.equals(MD5.md5(md5Str))) {
            // 根据 deviceId 进行推送
            wirelessDeviceService.lightSenceWarningPushByDeviceId(deviceId);
        }
    }


    /**
     * 列表
     */
    @GetMapping("/tSBdCarDevRelationList")
    public ResponseBean tSSsVehicleModelList(@RequestParam Map<String, Object> params, HttpServletRequest request) throws MyException {
        params.put("s_id", getCurrentUser(request).getS_id());
        params.put("user_id", getCurrentUser(request).getId());
        PageInfo info = wirelessDeviceService.queryPage(params);

        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", info);
    }

    /**
     * 新增或更新
     */
    @PostMapping("/tSBdCarDevRelationInsertUpdate")
    public ResponseBean tSSsVehicleModelInsertUpdate(@RequestBody Map<String, Object> params, HttpServletRequest request) throws MyException {

        // 通过car_id 和 type 查询是否有数据，如果有的话就更新，没有的话就新增
//        Map<String,Object> searchParams = new HashMap<>();
//        searchParams.put("carId",params.getCarId());
//        searchParams.put("type",params.getType());

        params.put("userId", getCurrentUser(request).getId());
        wirelessDeviceService.tSSsVehicleModelInsertUpdate(params);

        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", "");
    }

}